import { Body, Controller, Post, HttpCode, HttpStatus, Get, Headers, UnauthorizedException, Req, Res, Query } from '@nestjs/common';
import { Request, Response } from 'express';
import * as svgCaptcha from 'svg-captcha'
import { LoginService } from './login.service';
import { LoginDto } from './dto/login.dto';
import { UserInfo } from 'src/types/response';

@Controller('auth')
export class LoginController {
  constructor(private readonly loginService: LoginService) { }

  @Post('/login')
  @HttpCode(HttpStatus.OK)
  async login(@Body() loginDto: LoginDto, @Res() res: Response) {
    const result = await this.loginService.login(loginDto);

    res.cookie('refreshToken', result.data?.refreshToken, {
      httpOnly: true,
      secure: true,
      maxAge: 30 * 24 * 60 * 60 * 1000, // 30天
      sameSite: 'lax'
    })

    res.send({
      code: 200,
      msg: '登录成功',
      data: {
        token: result.data?.token
      }
    })
  }

  @Get('logout')
  @HttpCode(HttpStatus.OK)
  async logout(@Headers('authorization') authHeader: string) {
    if (!authHeader) {
      throw new UnauthorizedException('未提供认证token');
    }

    // 这里可以添加token黑名单逻辑
    return {
      success: true,
      message: '登出成功'
    };
  }

  @Get('profile')
  async getProfile(@Headers('authorization') authHeader: string): Promise<ResponseData<UserInfo>> {
    if (!authHeader) {
      throw new UnauthorizedException('未提供认证token');
    }

    const token = authHeader.replace('Bearer ', '');
    const isValid = await this.loginService.validateToken(token);

    if (!isValid) {
      throw new UnauthorizedException('无效的token');
    }

    return await this.loginService.getUserInfo(token);
  }


  @Get('getCaptchaCode')
  getCode(@Req() req: Request, @Res() res: Response) {
    const svgCaptchaIcon = svgCaptcha.create({
      size: 4,
      fontSize: 50,
      width: 100,
      height: 50,
      background: 'rgba(0, 0, 0, 1)'
    })

    console.log(svgCaptchaIcon.text, 'svgCaptchaIcon.text')
    req.session.code = svgCaptchaIcon.text;
    res.type('image/svg+xml');
    res.send(svgCaptchaIcon.data);
  }

  @Get('validateCaptchaCode')
  validateCaptchaCode(@Query('code') code: string, @Req() req: Request, @Res() res: Response) {
    console.log(code, req.session, "带哦")
    res.send({
      isSuccess: code === req.session.code
    })
  }

  @Get('refreshToken')
  @HttpCode(HttpStatus.OK)
  async refreshToken(@Req() req: Request, @Res() res: Response) {
    const refreshToken = req.cookies?.refreshToken;
    if (!refreshToken) {
      return res.status(401).send({ code: 401, msg: '未提供refreshToken' });
    }
    const result = await this.loginService.refreshToken(refreshToken);
    if (result.code !== 200) {
      return res.status(401).send(result);
    }
    res.send(result);
  }
}
